package com.qixin.modules.ea.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qixin.modules.ea.entity.*;
import com.qixin.modules.ea.mapper.*;
import com.qixin.modules.ea.service.IEaCommunicationsService;
import com.qixin.modules.ea.service.IEaCommunicationsServiceCopy;
import com.qixin.modules.ea.vo.CommunicationPageVo;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.util.ChangeIdToNameUtil;
import com.qixin.modules.eaBasic.util.WorkFlowUtil;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.rzInvoice.entity.EaBill;
import com.qixin.modules.rzInvoice.mapper.EaBillMapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Description: 通讯费报销单
 * @Author: qixin-boot
 * @Date:   2021-07-06
 * @Version: V1.0
 */
@Service
public class EaCommunicationsServiceImplCopy extends ServiceImpl<EaCommunicationsMapper, EaCommunications> implements IEaCommunicationsServiceCopy {

    @Autowired
    private EaCommunicationsMapper eaCommunicationsMapper;
    @Autowired
    private EaBookDetailMapper eaBookDetailMapper;
    @Autowired
    private EaTaskMapper eaTaskMapper;
    @Value(value = "${server.fileurl}")
    private String fileurl;
    @Autowired
    private ChangeIdToNameUtil changeIdToNameUtil;
    @Autowired
    private EaBillMapper eaBillMapper;
    @Autowired
    private WorkFlowUtil workFlowUtil;

    @Override
    @Transactional
    public Map<String,Object> saveMain(EaCommunications eaCommunications, List<EaBookDetail> eaBookDetailList) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        Object result = FillRuleUtil.executeRule("txbx_code", null);  //获取单据编号
        eaCommunications.setBillNo(result.toString());

        String saveType = eaCommunications.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            eaCommunications.setState(0);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaCommunications.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaCommunications.setId(Uuid32Util.getUUid());  //主键
        eaCommunicationsMapper.insert(eaCommunications);

        //查询通讯费报销单
        //新增待办
        EaTask eaTask = new EaTask();
        eaTask.setId(Uuid32Util.getUUid());
        eaTask.setFormType("10");  //单据类型:1通讯费报销单,2借款单,3还款单,4出差申请单,5出差申请变更单,6招待费申请单,7招待费申请变更单,8招待费报销单,9资金支付审批单,10通讯费报销单,11电话记录单
        eaTask.setAuditManId(eaCommunications.getAuditManId());   //审批人id
        eaTask.setAuditMan(eaCommunications.getAuditMan());    //审批人
        //提交类型:保存:add,提交:send
        if(saveType.equals("add")){  //add保存,send提交
            eaTask.setStatus("0");
        }else{
            eaTask.setStatus("1");
        }
        eaTask.setFormId(eaCommunications.getId());    //单据id
        eaTask.setFormCode(eaCommunications.getBillNo());   //单据编号
        eaTask.setMemo(eaCommunications.getCause());    //备注
        eaTask.setTotalFee(eaCommunications.getActualPayAmt()); //总金额
        eaTask.setSort("10");   //排序
        eaTask.setTitle("通讯费报销单");  //标题
        eaTask.setSendManId(eaCommunications.getPersonId());    //发送人id
        eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaCommunications.getPersonId()));    //发送人
        eaTask.setSendDepartId(eaCommunications.getDeptId());  //发送人部门id
        eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaCommunications.getDeptId()));   //发送人部门
        eaTask.setSendTime(new Date());    //发送时间
        eaTaskMapper.insert(eaTask);

        if(eaBookDetailList!=null && eaBookDetailList.size()>0) {
            for(EaBookDetail entity:eaBookDetailList) {
                //更新发票使用情况
                String fpid = entity.getFpid();
                EaBill eaBill = eaBillMapper.selectById(fpid);
                String isused = eaBill.getIsused();   //发票是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("发票号码:" + eaBill.getNumber() + "已被使用!");
                }else{
                    eaBill.setIsused("1");  //设置发票已使用
                    eaBillMapper.updateById(eaBill);
                }

                //外键设置
                entity.setBillId(eaCommunications.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBookDetailMapper.insert(entity);
            }
        }

        returnMap.put("id",eaCommunications.getId());
        returnMap.put("code","0");
        returnMap.put("message","保存成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> updateMain(EaCommunications eaCommunications,List<EaBookDetail> eaBookDetailList) {
        Map<String,Object> returnMap = new HashMap<String,Object>();

        //如果picture中有http://localhost:9092/qixin-boot/aaa.png,要处理只保留文件名
        String picture = eaCommunications.getPicture() != null ? eaCommunications.getPicture().toString() : "";
        String picture_final = picture.replaceAll(fileurl,"");;
        //设置最终的图片如:1111.png,2222.png
        eaCommunications.setPicture(picture_final);

        String saveType = eaCommunications.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            EaCommunications eaCommunications1 = eaCommunicationsMapper.selectById(eaCommunications.getId());
            eaCommunications.setState(eaCommunications1.getState());   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaCommunications.setState(1);   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaCommunicationsMapper.updateById(eaCommunications);

        //先将之前的相关发票状态改成未使用
        //获取原费用明细中的发票id
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("bill_id",eaCommunications.getId());
        List<EaBookDetail> eaBookDetailList1 = eaBookDetailMapper.selectByMap(paramsMap);
        for(EaBookDetail entity:eaBookDetailList1) {
            String fpid = entity.getFpid();  //发票id
            EaBill eaBill = eaBillMapper.selectById(fpid);
            eaBill.setIsused("0");   //设置状态为未使用
            eaBillMapper.updateById(eaBill);
        }

        //1.先删除子表数据
        eaBookDetailMapper.deleteByMainId(eaCommunications.getId());

        //修改待办
        Map<String,Object> paramsMap4 = new HashMap<String,Object>();
        paramsMap4.put("form_id",eaCommunications.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap4);
        for (EaTask eaTask:eaTaskList) {
            eaTask.setAuditManId(eaCommunications.getAuditManId());   //审批人id
            eaTask.setAuditMan(eaCommunications.getAuditMan());    //审批人
            //提交类型:保存:add,提交:send
            if(saveType.equals("add")){  //add保存,send提交
                eaTask.setStatus("0");
            }else{
                eaTask.setStatus("1");
            }
            eaTask.setFormId(eaCommunications.getId());    //单据id
            eaTask.setFormCode(eaCommunications.getBillNo());   //单据编号
            eaTask.setMemo(eaCommunications.getCause());    //备注
            eaTask.setTotalFee(eaCommunications.getActualPayAmt()); //总金额
            eaTask.setSendManId(eaCommunications.getPersonId());    //发送人id
            eaTask.setSendMan(changeIdToNameUtil.getPsnNameById(eaCommunications.getPersonId()));    //发送人
            eaTask.setSendDepartId(eaCommunications.getDeptId());  //发送人部门id
            eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaCommunications.getDeptId()));   //发送人部门
            eaTask.setSendTime(new Date());    //发送时间
            eaTaskMapper.updateById(eaTask);
        }

        //2.子表数据重新插入
        if(eaBookDetailList!=null && eaBookDetailList.size()>0) {
            for(EaBookDetail entity:eaBookDetailList) {
                //更新发票使用情况
                String fpid = entity.getFpid();
                EaBill eaBill = eaBillMapper.selectById(fpid);
                String isused = eaBill.getIsused();   //发票是否已使用
                if(isused.equals("1")){
                    throw new RuntimeException("发票号码:" + eaBill.getNumber() + "已被使用!");
                }else{
                    eaBill.setIsused("1");  //设置发票已使用
                    eaBillMapper.updateById(eaBill);
                }

                //外键设置
                entity.setBillId(eaCommunications.getId());
                entity.setId(Uuid32Util.getUUid());
                eaBookDetailMapper.insert(entity);
            }
        }

        returnMap.put("id",eaCommunications.getId());
        returnMap.put("code","0");
        returnMap.put("message","编辑成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> delMain(String id) {
        Map<String,Object> retrunMap = new HashMap<String,Object>();

        //通讯费报销单状态为未提交时,可以删除
        EaCommunications eaCommunications = eaCommunicationsMapper.selectById(id);
        Integer billStatus = eaCommunications.getState();   //单据状态:0时可以删除,其它提示
        if(!(billStatus == 0)){
            retrunMap.put("code","-1");
            retrunMap.put("message","通讯费报销单为未提交时,才能被删除!");
            return retrunMap;
        }

        //将相应发票状态改成未使用
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("bill_id",id);
        List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectByMap(paramsMap);
        if(eaBookDetailList != null && eaBookDetailList.size() > 0){
            for (EaBookDetail eaBookDetail: eaBookDetailList) {
                String fpid = eaBookDetail.getFpid();   //发票id
                EaBill eaBill = eaBillMapper.selectById(fpid);
                eaBill.setIsused("0");  //设置发票未使用
                eaBillMapper.updateById(eaBill);
            }
        }

        //删除相应的待办
        Map<String,Object> paramaMap = new HashMap<String,Object>();
        paramaMap.put("form_id",id);
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramaMap);
        if(eaTaskList != null && eaTaskList.size() > 0){
            EaTask eaTask = eaTaskList.get(0);

            //删除相应的工作流
            workFlowUtil.deleteWorkFlowById(eaTask.getWorkflowTaskId(),eaTask.getProcinstId());

            eaTaskMapper.deleteById(eaTask.getId());
        }

        //删除主表数据
        eaBookDetailMapper.deleteByMainId(id);
        eaCommunicationsMapper.deleteById(id);

        retrunMap.put("code","0");
        retrunMap.put("message","删除成功!");
        return retrunMap;
    }

    //查询通讯费报销单详情
    @Override
    public Map<String,Object> selectById(String id) {
        Map<String,Object> queryWrapper = new HashMap<String,Object>();
        queryWrapper.put("id",id);  //通讯费报销单id
        queryWrapper.put("page",0);
        queryWrapper.put("limit",0);
        List<EaCommunications> eaCommunicationsList = eaCommunicationsMapper.selectEaCommunications(queryWrapper);
        Map<String,Object> returnMap = new HashMap<String,Object>();

        if(eaCommunicationsList.size() > 0){
            for (EaCommunications eaCommunications : eaCommunicationsList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaCommunications, SerializerFeature.WriteMapNullValue), Map.class);

                if (StrUtil.isNotBlank(map.get("recPersonId").toString())){
                    // 发票归属人 id转名称
                    String recPersonIdName = changeIdToNameUtil.getPsnNameById(map.get("recPersonId").toString());
                    map.put("recPersonIdName",recPersonIdName);
                }

                //格式化时间-创建时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间-更新日期
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);

                //格式化时间-单据日期
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //添加图片
                String picture = map.get("picture") != null ? map.get("picture").toString() : "";
                List<Map<String,Object>> fileList = GetUrlUtil.getUrl(picture,fileurl);

                //添加图片fileList
                map.put("fileList",fileList);

                //添加相应的费用明细
                List<EaBookDetail> eaBookDetailList = eaBookDetailMapper.selectBookDetails(eaCommunications.getId());
                List<Map<String,Object>> mapList2 = new ArrayList<Map<String,Object>>();
                if(eaBookDetailList.size() > 0){
                    for (EaBookDetail eaBookDetail: eaBookDetailList) {
                        Map map2 = JSON.parseObject(JSON.toJSONString(eaBookDetail, SerializerFeature.WriteMapNullValue), Map.class);

                        // 发票归属人 id转名称
                        String fygsrName = changeIdToNameUtil.getPsnNameById(eaBookDetail.getFygsr());
                        map2.put("fygsrName",fygsrName);

                        //格式化时间
                        Long kprq = map2.get("kprq") != null ? Long.parseLong(map2.get("kprq").toString()) : null;
                        String kprqStr = DateFormatUtil.formatDateyyMMdd(kprq);
                        map2.put("kprq",kprqStr);

                        //格式化时间
                        Long createTime2 = map2.get("createTime") != null ? Long.parseLong(map2.get("createTime").toString()) : null;
                        String createTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(createTime2);
                        map2.put("createTime",createTimeStr2);

                        //格式化时间
                        Long updateTime2 = map2.get("updateTime") != null ? Long.parseLong(map2.get("updateTime").toString()) : null;
                        String updateTimeStr2 = DateFormatUtil.formatDateyyMMddHHmmss(updateTime2);
                        map2.put("updateTime",updateTimeStr2);

                        mapList2.add(map2);
                    }
                }

                //将费用明细加到eaBookDetailList节点
                map.put("eaBookDetailList",mapList2);
                returnMap = map;
            }
        }
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String, Object> audit(EaTaskVo eaTaskVo) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String id = EmptyUtil.checkNull(eaTaskVo.getId());   //单据id
//        String auditManId = EmptyUtil.checkNull(eaTaskVo.getAuditManId());   //审批人id
//        String auditMan = EmptyUtil.checkNull(eaTaskVo.getAuditMan());   //审批人
        String auditComment = EmptyUtil.checkNull(eaTaskVo.getAuditComment());   //审批意见
        int status = eaTaskVo.getStatus();   //单据状态:2通过,3退回

        //获取通讯费报销单-更新状态
        EaCommunications eaCommunications = eaCommunicationsMapper.selectById(id);
        eaCommunications.setState(status);
        eaCommunicationsMapper.updateById(eaCommunications);

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("form_id",eaCommunications.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap);
        if(eaTaskList != null && eaTaskList.size() > 0){
            EaTask eaTask = eaTaskList.get(0);
            //eaTask.setAuditManId(auditManId);
            //eaTask.setAuditMan(auditMan);
            eaTask.setAuditComment(auditComment);
            eaTask.setStatus(eaTaskVo.getStatus().toString());

            try {
                if((status == 3)|| (status == 2)){
                    eaTask.setFinishTime(new Date());   //完成时间
                }
                eaTask.setAuditTime(new Date());    //审批时间
                eaTaskMapper.updateById(eaTask);

                returnMap.put("code","0");
                returnMap.put("message","审核成功!");
                return returnMap;
            }catch (Exception e){
                returnMap.put("code","-1");
                returnMap.put("message","系统异常,审核失败!");
                return returnMap;
            }
        }else{
            returnMap.put("code","-1");
            returnMap.put("message","待办不存在!");
            return returnMap;
        }
    }

    //查询通讯费报销单列表
    @Override
    public Map<String, Object> list(CommunicationPageVo communicationPageVo) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String page = EmptyUtil.checkNull(communicationPageVo.getPage());
        String limit = EmptyUtil.checkNull(communicationPageVo.getLimit());
        String keyword = EmptyUtil.checkNull(communicationPageVo.getKeyword());
        String userid = EmptyUtil.checkNull(loginUser.getId());   //用户id
        String status = EmptyUtil.checkNull(communicationPageVo.getStatus());   //状态
        String billNo = EmptyUtil.checkNull(communicationPageVo.getBillNo());   //单据编号(pc)
        String explainStr = EmptyUtil.checkNull(communicationPageVo.getCasue());   //事由(pc)
        String billDateBegin = EmptyUtil.checkNull(communicationPageVo.getBillDateBegin());   //单据日期-开始(pc)
        String billDateEnd = EmptyUtil.checkNull(communicationPageVo.getBillDateEnd());   //单据日期-结束(pc)
        String sysOrgCode = EmptyUtil.checkNull(communicationPageVo.getSysOrgCode());   //所属组织(pc)

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        String keyword1 = "%" + keyword + "%";
        paramsMap.put("keyword",keyword1);
        paramsMap.put("page",(Integer.parseInt(page) -1) * Integer.parseInt(limit));
        paramsMap.put("limit",Integer.parseInt(limit));
        paramsMap.put("userid",userid);
        paramsMap.put("status",status);
        paramsMap.put("billNo",billNo);
        paramsMap.put("explainStr",explainStr);
        paramsMap.put("billDateBegin",billDateBegin);
        paramsMap.put("billDateEnd",billDateEnd);
        paramsMap.put("sysOrgCode",sysOrgCode);
        List<EaCommunications> eaCommunicationsList = eaCommunicationsMapper.selectEaCommunications(paramsMap);

        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        if(eaCommunicationsList.size() > 0){
            for (EaCommunications eaCommunications : eaCommunicationsList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaCommunications, SerializerFeature.WriteMapNullValue), Map.class);

                //格式化时间
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //格式化时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);

                mapList.add(map);
            }
        }

        int count = 0;
        paramsMap.put("page",0);
        paramsMap.put("limit",0);
        paramsMap.put("keyword",keyword1);
        paramsMap.put("userid",userid);
        List<EaCommunications> list2 = eaCommunicationsMapper.selectEaCommunications(paramsMap);
        count = list2.size();

        returnMap.put("records",mapList);
        returnMap.put("total",count);
        return returnMap;
    }

    @Override
    public EaCommunications queryById(String billId) {
        return eaCommunicationsMapper.selectById(billId);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for(Serializable id:idList) {
            eaBookDetailMapper.deleteByMainId(id.toString());
            eaCommunicationsMapper.deleteById(id);
        }
    }

}
